package com.example.demo.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.example.demo.framework.CustomPage;
import com.example.demo.framework.base.BaseService;

@Service
public class StorageService extends BaseService {

	@SuppressWarnings("unchecked")
	public CustomPage findAfterSaleTrade(int pageNo, int pageSize, String tradeID, Long userID, String username,
			Integer status) {
		CustomPage cPage = new CustomPage();
		String field = "new Map(a.tradeID as tradeID,t.receiverName as receiverName, o.itemID as itemID, o.skuTitle as skuTitle,t.tID as tID, "
				+ "t.totalFee as totalFee, t.postFee as postFee, a.logisticsNumberBack as logisticsNumberBack, a.expressBack as expressBack, "
				+ "a.createtime as createtime,a.issueType as issueType,a.issueContent as issueContent, a.status as status, "
				+ "a.issueContent as issueContent,a.reply as reply, a.backAddress as backAddress )";
		StringBuilder hql = new StringBuilder(
				"SELECT %s FROM AfterSale a LEFT JOIN Trade t ON a.tradeID=t.tradeID LEFT JOIN Order o on t.tradeID=o.tradeID LEFT JOIN UserInfo u ON t.userID=u.userID WHERE 1=? ");
		List<Object> values = new ArrayList<>();
		values.add(1);
		if (StringUtils.isNotEmpty(tradeID)) {
			hql.append(" and a.tradeID = ? ");
			values.add(tradeID);
		}
		if (status != null) {
			hql.append(" and a.status = ? ");
			values.add(status);
		}
		if (userID != null) {
			hql.append(" and t.userID = ? ");
			values.add(userID);
		}
		if (StringUtils.isNotEmpty(username)) {
			hql.append(" and u.username = ? ");
			values.add(username);
		}
		cPage.setContent(createQuery(String.format(hql.toString(), field), values.toArray())
				.setFirstResult(CustomPage.getStartOfPage(pageNo, pageSize)).setMaxResults(pageSize).getResultList());
		cPage.setTotal(
				(long) createQuery(String.format(hql.toString(), SQL_COUNT), values.toArray()).getSingleResult());
		cPage.setPageNo(pageNo+1);
		cPage.setSize(pageSize);
		return cPage;
	}

}
